module ActsAsDynamic
  module AutoCompleteActions

    def nav_auto_complete_for(object, methods, options = {})
      methods = methods.is_a?(Array) ? methods : [methods]
      method_suffix = methods.map(&:to_s).join('_and_')
      define_method("auto_complete_for_#{object}_#{method_suffix}") do
        like = methods.map {|m| "LOWER(#{m}) LIKE ?"}.join(' OR ')
        conditions = [like]
        conditions << methods.map {|m| '%' + params[object][method_suffix].to_s.downcase + '%'}
        model = (options.delete(:model) || object)
        model_class = model.to_s.camelize.constantize
        extra_conditions = options.delete(:conditions)
        # Condiciones de busqueda
        find_options = { 
          :conditions => conditions.flatten, 
          :order => "#{methods.first} ASC",
          :limit => 10 }.merge!(options)
        # Condiciones externas (pasadas como parámetro)
        model_class.with_scope(:find => {:conditions => extra_conditions}) do
          @items = model_class.find(:all, find_options)
        end
        @methods = methods
        render :inline => <<-erb_end
          <ul>
            <% for item in @items %>
              <li id="<%= "#{object}_auto_complete_id_" + item.id.to_s %>"><%= @methods.map {|m| item.send(m)}.join(' - ') %></li>
            <% end %>
          </ul>
        erb_end
      end
    end
  
  end
end

ActionController::Base.extend ActsAsDynamic::AutoCompleteActions
